package com.xiaozhuai.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.text.SimpleDateFormat;

public class JsonUtils {
    /**
     * Object转JSON
     * @param o
     * @return
     * @throws JsonProcessingException
     */
    public static String getJson(Object o ) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
        return mapper.writeValueAsString(o);
    }

    public static String getJson(Object o ,String dateFormat) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
        //使用Java自带的格式化工厂来格式化时间
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        String format = sdf.format(o);
        try {
            return mapper.writeValueAsString(format);
        }catch (Exception e){
            return "格式错误";
        }
    }
}
